// filepath: /d:/aiWorkspace/video-generation-app/video-generation-app/src/api/video-api.ts
import axios from './axios-config';
import { fetchEventSource } from '@microsoft/fetch-event-source';

const url_prefix = '/rag';

export const uploadDocument = async (documentFile: File) => {
  const formData = new FormData();
  formData.append('document', documentFile);

  try {
    const response = await axios.post(url_prefix + '/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    if (response.data.error) {
      throw new Error(response.data.error);
    }
    return response.data.success;
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : String(error));
  }
};

export const ask = async (question: string, onmessage: (event) => void) => {

  const token = localStorage.getItem('token');
  const fetchEventUrl = '/api' + url_prefix + '/ask';
  const eventData = { value: '' };
  
  const ctrl = new AbortController();
  try {
    fetchEventSource(fetchEventUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ question: question }),
      signal: ctrl.signal,
      async onopen(response) {
        if (response.ok && response.status === 200) {
          console.log('EventSource 连接已建立');
        } else {
          throw new Error(`EventSource 连接失败，状态码: ${response.status}`);
        }
      },
      onmessage(event) {
        // 处理接收到的事件数据
        onmessage(event);
        // eventData.value += event.data + '\n';
      },
      onclose() {
        console.log('EventSource 连接已关闭');
      },
      onerror(error) {
        console.log('EventSource 请求出错:', error);
        // 可以选择在这里进行重试逻辑
        throw error;
      }
    });

  } catch (error) {
    throw new Error(error instanceof Error ? error.message : String(error));
  }
};

/**
 * 删除会话
 * @param userId 用户ID
 * @param sessionId 会话ID
 * @returns {Promise<boolean>} 删除成功返回true，失败返回false
 */
export const deleteSession = async (userId: string, sessionId: string) => {
  try {
    const response = await axios.post('/chat/ai/deleteSession', {
      userId,
      sessionId
    });
    return response.data;
  } catch (error) {
    console.error('删除会话失败:', error);
    throw new Error(error instanceof Error ? error.message : String(error));
  }
};